package com.hm.ruiji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hm.ruiji.common.R;
import com.hm.ruiji.dto.DishDto;
import com.hm.ruiji.entity.Category;
import com.hm.ruiji.entity.Dish;
import com.hm.ruiji.entity.DishFlavor;
import com.hm.ruiji.service.CategoryService;
import com.hm.ruiji.service.DishFlavorService;
import com.hm.ruiji.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Resource
    private DishService dishService;

    //@Resource
    //private DishFlavorService dishFlavorService;

    @Resource
    private CategoryService categoryService;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        //构造分页构造器
        Page<DishDto> dishDtoPageInfo = new Page(page,pageSize);
        Page<Dish> pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        // 添加过滤条件
        queryWrapper.like(name != null, Dish::getName,name);
        //添加排序条件，根据sort排序
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行查询
        dishService.page(pageInfo,queryWrapper);


        /*
            dish中无分类名属性
            将分类名根据分类id查询并存储到DTO对象
         */
        /**
         * 拷贝对象
         * Params:
         *      source – the source bean
         *      target – the target bean
         */
        BeanUtils.copyProperties(pageInfo, dishDtoPageInfo, "records");

        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            //  创建DTO对象存储属性
            DishDto dishDto = new DishDto();
            //  获取分类id
            Long categoryId = item.getCategoryId();
            //  根据id查分类名称
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //  将dish基本信息拷贝到dto对象存储
                BeanUtils.copyProperties(item, dishDto);
                //  将分类名保存
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPageInfo.setRecords(list);

        return R.success(dishDtoPageInfo);
    }

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("菜品信息：" + dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        return R.success("添加菜品成功");
    }

    /**
     * 根据id查询菜品及对应口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("菜品修改信息：" + dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("菜品信息修改成功");
    }

    /**
     * 启售停售
     * @param status 状态码
     * @param ids id集合
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        log.info("状态："+status+"||ids：" + ids);
        //for (Long id : ids) {
        //    UpdateWrapper<Dish> wrapper = new UpdateWrapper<>();
        //    wrapper.eq("id", id);
        //    wrapper.set("status", ztm);
        //    dishService.update(wrapper);
        //}
        UpdateWrapper<Dish> wrapper = new UpdateWrapper();
        wrapper.set("status", status).in("id", ids);
        dishService.update(wrapper);
        return R.success("菜品状态修改成功");
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> removeWithFlavor(@RequestParam List<Long> ids) {
        log.info("ids:" + ids);

        boolean b = dishService.removeWithFlavor(ids);
        if (!b) return R.error("你选中的菜品中包含在售产品，请停售后再删除");
        //List<Long> idList = new ArrayList<>();
        //List<Dish> dishes = dishService.listByIds(ids);
        //for (Dish dish : dishes) {
        //    if (dish.getStatus() == 0){
        //        idList.add(dish.getId());
        //    }
        //}
        //dishService.removeByIdsWithFlavor(idList);

        //if (ids.size() > idList.size()){
        //    return R.success("您选中的菜品中包含的已停售菜品删除完成");
        //}else if (idList.size() ==0){
        //    return R.success("您选中的菜品在售，请停售后在删除");
        //}
        //
        //// 删除口味
        //LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        //List<Long> flavorIdList = new ArrayList<>();
        //for (Long id : ids) {
        //    wrapper.eq(DishFlavor::getDishId,id);
        //    List<DishFlavor> list = dishFlavorService.list(wrapper);
        //    for (DishFlavor dishFlavor : list) {
        //      flavorIdList.add(dishFlavor.getId());
        //    }
        //}
        //dishFlavorService.removeByIds(flavorIdList);
        return R.success("菜品删除成功");
    }

    /**
     * 根据id查询
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<Dish>> list(Dish dish) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        // 查询条件
        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());

        // 查询起售的菜品 0停售  1起售
        wrapper.eq(Dish::getStatus, 1);
        // 排序条件
        wrapper.orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(wrapper);
        return R.success(list);
    }

}
